from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
from pydantic import BaseModel
from pathlib import Path
from typing import Union
import os, subprocess, json

from api.api import router

app = FastAPI()
app.include_router(router)

# from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",
        "http://127.0.0.1:5173",
        "http://localhost:5174",
        "http://127.0.0.1:5174",
    ],  # 允许本机两种端口访问（5173/5174）
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
FILE_PATH = Path(__file__).with_name("test.xlsx")
SCRIPT_DIR = os.path.join(os.path.dirname(__file__), "models")


class ModelReq(BaseModel):
    model_name: str


@app.post("/load-GestureModel")
def run_detect(req: ModelReq):
    script_map = {
        "手势识别模型A": "GestureTest.py"
    }
    script = script_map.get(req.model_name)
    if not script or not os.path.isfile(os.path.join(SCRIPT_DIR, script)):
        raise HTTPException(status_code=404, detail="模型不存在")
    proc = subprocess.run(["python", os.path.join(SCRIPT_DIR, script)], capture_output=True, text=True, check=True)
    return json.loads(proc.stdout)


@app.post("/read-excel")
def read_excel():
    if not FILE_PATH.exists():
        raise HTTPException(status_code=404, detail="注意！文件不存在哦~")
    df = pd.read_excel(FILE_PATH, engine="openpyxl")
    return df.fillna('').to_dict(orient="records")  # 空串可接受


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}
